﻿#region 文件信息

/*----------------------------------------------------------------
//
// 文件名称：
// 文件功能描述：
// 设计要求：
//
// 文 件 名：    UserService
// 创建者：      杨程
// 创建日期：	    2023/1/7 20:39:05

//----------------------------------------------------------------*/

#endregion

namespace Vampirewal.Admin.Server.RpcServices.Service
{
    /// <summary>
    /// RPC用户服务
    /// </summary>
    public partial class UserService : RpcServiceBasic
    {
        private RoleService RoleServer { get; set; }


        /// <summary>
        ///
        /// </summary>
        public UserService(RoleService roleService)
        {
            RoleServer = roleService;
            //构造函数
        }

        #region [     新增     ]

        /// <summary>
        /// 新增用户
        /// </summary>
        /// <param name="callContext"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        [LogWrite]
        [ActionFilter]
        [Description("新增用户")]
        [TouchRpc(MethodFlags = MethodFlags.IncludeCallContext)]
        public bool CreateUser(ICallContext callContext, Sys_User entity)
        {
            callContext.CheckCaller(out Sys_User user);

            entity.CreateBy = user.Name;
            entity.CreateUserId = user.BillId;

            var repUser = SqlSugarRepository<Sys_User>();

            try
            {
                repUser.CurrentBeginTran();

                var result = repUser.Insert(entity);

                repUser.CurrentCommitTran();

                return result == 1;
            }
            catch (Exception ex)
            {
                repUser.CurrentRollbackTran();
                throw ex;
            }
        }

        #endregion

        #region [     删除     ]

        /// <summary>
        /// 删除用户(将State字段修改为2)
        /// </summary>
        /// <param name="callContext"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        [LogWrite]
        [ActionFilter]
        [Description("删除用户(将State字段修改为2)")]
        [TouchRpc(MethodFlags = MethodFlags.IncludeCallContext)]
        public bool DeleteUser(ICallContext callContext, Sys_User entity)
        {
            var repUser = SqlSugarRepository<Sys_User>();
            try
            {
                callContext.CheckCaller(out Sys_User user);
                entity.State = 2;
                

                repUser.CurrentBeginTran();
                entity.UpdateBy = user.Name;
                entity.UpdateTime = DateTime.Now;
                entity.UpdateUserId = user.BillId;
                repUser.Delete(entity);

                repUser.CurrentCommitTran();

                return true;
            }
            catch (Exception ex)
            {
                repUser.CurrentRollbackTran();
                throw ex;
            }

            return false;
        }

        #endregion

        #region [     修改     ]

        /// <summary>
        /// 修改用户信息
        /// </summary>
        /// <param name="callContext"></param>
        /// <param name="entity"></param>
        /// <returns></returns>
        [LogWrite]
        [ActionFilter]
        [Description("新增字典类型")]
        [TouchRpc(MethodFlags = MethodFlags.IncludeCallContext)]
        public bool UpdateUser(ICallContext callContext, Sys_User entity)
        {
            var repUser = SqlSugarRepository<Sys_User>();
            try
            {
                callContext.CheckCaller(out Sys_User user);

                repUser.CurrentBeginTran();
                entity.UpdateBy = user.Name;
                entity.UpdateTime = DateTime.Now;
                entity.UpdateUserId = user.BillId;
                repUser.Update(entity);

                repUser.CurrentCommitTran();

                return true;
            }
            catch (Exception ex)
            {
                repUser.CurrentRollbackTran();
                throw ex;
            }

            return false;
        }

        #endregion

        #region [     查询     ]

        /// <summary>
        /// 分页查询用户
        /// </summary>
        /// <param name="callContext"></param>
        /// <param name="request"></param>
        /// <returns></returns>
        [LogWrite]
        [Description("分页查询用户")]
        [ActionFilter]
        [TouchRpc(MethodFlags = MethodFlags.IncludeCallContext)]
        public PageContainer<Sys_User> GetPageListUser(ICallContext callContext, UserRequest request)
        {
            var repUser = SqlSugarRepository<Sys_User>();
            int total = 0;
            int totalPage = 0;

            var OrgIds = RoleServer.GetRoleDataScope(callContext);

            callContext.CheckCaller(out Sys_User user);
            var dbresult = repUser.AsQueryable().Where(f => f.TenantId == user.TenantId)
                                                              .WhereIF(!string.IsNullOrEmpty(request.OrgId), f => f.OrgId == request.OrgId)
                                                              .WhereIF(!string.IsNullOrEmpty(request.OrgName), f => f.OrgName.Contains(request.OrgName))
                                                              .WhereIF(!string.IsNullOrEmpty(request.UserName), f => f.Name.Contains(request.UserName))
                                                              .Where(f => OrgIds.Contains(f.OrgId))
                                                              .ToPageList(request.Page, request.Limit, ref total, ref totalPage);

            PageContainer<Sys_User> container = new PageContainer<Sys_User>();
            container.Data = dbresult;
            container.TotalCount = total;
            container.PageCount = totalPage;
            container.Count = dbresult.Count;

            return container;
        }

        /// <summary>
        /// 通过BillId查找用户
        /// </summary>
        /// <param name="callContext"></param>
        /// <param name="BillId"></param>
        /// <returns></returns>
        [Description("通过BillId查找用户")]
        [ActionFilter]
        [TouchRpc(MethodFlags = MethodFlags.IncludeCallContext)]
        public Sys_User GetUserById(ICallContext callContext, string BillId)
        {
            callContext.CheckCaller(out Sys_User user);
            return SqlSugarRepository<Sys_User>().Single(s => s.BillId == BillId);
        }

        /// <summary>
        /// 根据角色ID获取用户列表
        /// </summary>
        /// <param name="callContext"></param>
        /// <param name="RoleId">角色ID</param>
        /// <returns></returns>
        [Description("根据角色ID获取用户列表")]
        [ActionFilter]
        [TouchRpc(MethodFlags = MethodFlags.IncludeCallContext)]
        public List<Sys_User> GetUserListByRoleId(ICallContext callContext, string RoleId)
        {
            callContext.CheckCaller(out Sys_User user);
            var repUser = SqlSugarRepository<Sys_User>();

            var UserIds = repUser.Change<Sys_UserRole>().AsQueryable()
                                                    .InnerJoin<Sys_RoleTemplate>((u1, r1) => r1.BillId == u1.RoleId)
                                                    .Where((u1, r1) => r1.TenantId == user.TenantId && r1.BillId == RoleId)
                                                    .Select(s => s.UserId)
                                                    .ToList();

            return repUser.ToList(s => UserIds.Contains(s.BillId) && !s.IsAdmin);
        }

        /// <summary>
        /// 根据机构ID获取当前部门的负责人信息
        /// </summary>
        /// <param name="callContext"></param>
        /// <param name="OrgId">机构ID</param>
        /// <returns></returns>
        [Description("根据机构ID获取当前部门的负责人信息")]
        [ActionFilter]
        [TouchRpc(MethodFlags = MethodFlags.IncludeCallContext)]
        public Sys_User GetCurrentDeptLeaderByOrgId(ICallContext callContext, string OrgId)
        {
            return SqlSugarRepository<Sys_User>().FirstOrDefault(s => s.OrgId == OrgId && s.IsCurrentDeptLeader && s.State == 1);
        }

        #endregion
    }
}